package com.qlk.vorder.interceptor;

import com.qlk.common.utils.cookie.CookieUtils;
import com.qlk.common.web.context.ExcludeRequstPath;
import com.qlk.common.web.interceptor.AbstractHandlerInterceptorAdapter;
import com.qlk.vorder.utils.login.LoginUser;
import com.qlk.vorder.utils.login.UserContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zhaoyanan on 2016/8/5.
 */
public class LoginCookieInterceptor extends AbstractHandlerInterceptorAdapter {

    private final static Log LOG = LogFactory.getLog(LoginCookieInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        if (ExcludeRequstPath.isExclude(getExcludePaths(), uri)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("in request [" + uri + "], this url is excludeRequstPath");
            }
            return true;
        }

        LoginUser user = UserContext.get().getUser();
        if (user == null){
//            读取cookie
            user = new LoginUser();
            //用户id
            String userId = CookieUtils.getCookieValueSimple(request,"userId");
            //用户账号
            String userName = CookieUtils.getCookieValueSimple(request,"userName");
            String userRealName = CookieUtils.getCookieValueSimple(request,"userRealName");
            String userNickName = CookieUtils.getCookieValueSimple(request,"userNickName");
            String userIdentity = CookieUtils.getCookieValueSimple(request,"userIdentity");
            String userToken = CookieUtils.getCookieValueSimple(request,"userToken");
            user.setUserId(userId);
            user.setUserName(userName);
            user.setUserRealName(userRealName);
            user.setUserNickName(userNickName);
            user.setUserIdentity(userIdentity);
            user.setUserToken(userToken);
            UserContext.set(user);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
